package cn.tataben.sharding.base;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Generator {

	/**
	 * 下划线转大驼峰
	 * @param className
	 */
	public static String underlineToBigCamel(String className){
		return underlineToSmallCamel(className.toUpperCase().substring(0, 1) + className.substring(1));
	}

	/**
	 * 大驼峰转小驼峰
	 * @param className
	 */
	public static String bigCamelToSmallCamel(String className) {
		return className.toLowerCase().substring(0, 1) + className.substring(1);
	}

	/**
	 * 下划线转小驼峰
	 * @param propertyName
	 */
	public static String underlineToSmallCamel(String propertyName){
		if (propertyName == null || "".equals(propertyName.trim())){
			return "";
		}
		int len = propertyName.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = propertyName.charAt(i);
			if (c == '_'){
				if (++i < len) {
					sb.append(Character.toUpperCase(propertyName.charAt(i)));
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 驼峰转下划线
	 * @param property
	 */
	public static String camelToUnderline(String property){
		if (property == null || "".equals(property.trim())){
			return "";
		}
		int len = property.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = property.charAt(i);
			if (Character.isUpperCase(c)){
				sb.append("_");
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * Bean转换
	 * @param from
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public static <B, O> B convert(O from, Class<B> to) throws Exception {
		Field[] ofs = from.getClass().getDeclaredFields();
		Field[] nfs = to.getDeclaredFields();
		B b = to.newInstance();
		for (int i = 0; i < nfs.length; i++) {
			for (int k = 0; k < ofs.length; k++) {
				if (ofs[k].getName().equals(nfs[i].getName())) {
					nfs[i].setAccessible(true);
					ofs[k].setAccessible(true);
					nfs[i].set(b, ofs[k].get(from));
					break;
				}
			}
		}
		return b;
	}

	/**
	 * Bean批量转换
	 * @param froms
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public static <B, O> List<B> convert(List<O> froms, Class<B> to) throws Exception {
		List<B> bs = new ArrayList<B>();
		if (froms != null && froms.size() > 0) {
			Field[] ofs = froms.get(0).getClass().getDeclaredFields();
			Field[] nfs = to.getDeclaredFields();
			B b = null;
			for (int m = 0; m < froms.size(); m++) {
				b = to.newInstance();
				for (int i = 0; i < nfs.length; i++) {
					for (int k = 0; k < ofs.length; k++) {
						if (ofs[k].getName().equals(nfs[i].getName())) {
							nfs[i].setAccessible(true);
							ofs[k].setAccessible(true);
							nfs[i].set(b, ofs[k].get(froms.get(m)));
							break;
						}
					}
				}
				bs.add(b);
			}
		}
		return bs;
	}

}